package study.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//逆波兰计算器
public class PolandNotation {
    public static void main(String[] args) {
        String suffixExpression = "3 4 + 5 * 6 -";
        //思路
        //1.将3 4 + 5 * 6 - 放到ArrayList中
        //2.将ArrayList传递给一个方法，遍历ArrayList 配合桟 完成计算
        List<String> list = getListString(suffixExpression);
        int res = calculate(list);
        System.out.println("计算结果是：" + res);


    }

    public static List<String> getListString(String suffixExpression){
        //将suffixExpression分割
        String[] split = suffixExpression.split(" ");
        List<String> list = new ArrayList<>();
        for (String ele : split) {
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> list){
        Stack<String> stack = new Stack<>();
        for (String item : list) {
            if (item.matches("\\d+")){
                stack.push(item);
            }else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int result = 0;
                if ("+".equals(item)){
                    result = num1 + num2;
                }else if ("-".equals(item)){
                    result = num2 - num1;
                }else if ("*".equals(item)){
                    result = num1 * num2;
                }else if ("/".equals(item)){
                    result = num2 / num1;
                }else {
                    throw new RuntimeException("运算符错误");
                }

                stack.push("" + result);
            }
        }

        return Integer.parseInt(stack.pop());
    }
}
